package com.jch.sc.client;

import com.jch.sc.codec.ObjDecoder;
import com.jch.sc.codec.ObjEncoder;
import com.jch.sc.msg.Request;
import com.jch.sc.msg.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ClientSocket implements Runnable {

    private ChannelFuture channelFuture;

    @Override
    public void run() {
        EventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap()
                .group(worker)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.AUTO_READ, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new ObjDecoder(Response.class), // 解码服务端的响应信息
                                new ObjEncoder(Request.class), // 编码客户端请求信息
                                new ClientHandler()
                        );
                    }
                });
        try {
            ChannelFuture cf = b.connect("127.0.0.1", 1129).sync();
            this.channelFuture = cf;
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

    public ChannelFuture getChannelFuture() {
        return channelFuture;
    }

    public void setChannelFuture(ChannelFuture channelFuture) {
        this.channelFuture = channelFuture;
    }
}
